package com.homer.iot.esptouch.model;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.homer.iot.esptouch.tcp.UartTCPUtil;

public class Device {

	private String deviceIP;

	private String deviceID;

	private List<Slaver> slaverList;

	public Device(String deviceIP, String deviceID/*, List<Slaver> slaverList*/) {
		super();
		this.deviceIP = deviceIP;
		this.deviceID = deviceID;
	}

	public String getDeviceIP() {
		return deviceIP;
	}

	public String getDeviceID() {
		if (null == deviceID) {
			return UartTCPUtil.getDeviceID(deviceIP);
		} else
			return deviceID;
	}

	public List<Slaver> getSlaverList() {
		List<Slaver> tmpList = new ArrayList<Slaver>();
		int tryCount = 3;
		for(int i = 0;i<tryCount;i++){
			slaverList = UartTCPUtil.getSlaverList(deviceIP);			
			if (null != slaverList) {
				for (Iterator iterator = slaverList.iterator(); iterator.hasNext();) {
					Slaver slaver = (Slaver) iterator.next();
					slaver.setDevice(this);
					tmpList.add(slaver);
				}
				break;
			}

			
		}
		
		this.slaverList = tmpList;	
		return tmpList;
	}

	public boolean isOnline() {
		return UartTCPUtil.isOnline(deviceIP);
	}


	public boolean deleteSlaver(String slaverId)
			throws UnsupportedEncodingException {
		short id = Short.parseShort(slaverId);
		return UartTCPUtil.deleteSlaver(deviceIP, id);
	}

	public boolean resetDefault() {
		return UartTCPUtil.controlFactoryReset(deviceIP);
	}

	public boolean saveParam() {
		return UartTCPUtil.saveParam(deviceIP);

	}

	public boolean allowJoinNewDevice(boolean allow) {
		if (allow) {
			return UartTCPUtil.allowJoinNewDevice(deviceIP, (byte) 0xff);
		} else {
			return UartTCPUtil.allowJoinNewDevice(deviceIP, (byte) 0x00);
		}
	}

	public boolean controlColorLamp(byte R, byte G, byte B, byte whiteLight) {
		return UartTCPUtil.controlColorLamp(deviceIP, R, G, B, whiteLight);
	}

	public boolean setAlarmMode(boolean isAlarm)
	{
		if(isAlarm) {
			return UartTCPUtil.setAlarmMode(deviceIP, (byte)0x01);
		} else {
			return UartTCPUtil.setAlarmMode(deviceIP, (byte)0x00);
		}
	}
	
	public boolean playDoorRing()
	{
		byte[] action = {0x01, 0x04};
		return UartTCPUtil.playSound(deviceIP, action);
	}
}
